package com.example.systemend.controller;



import com.example.systemend.pojo.Goods;
import com.example.systemend.pojo.Message;
import com.example.systemend.pojo.User;
import com.example.systemend.service.UserService;
import com.example.systemend.util.JwtUtil;
import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 权哥
 * @version 1.0
 * @date 2022/6/9 23:38
 */
@RestController
public class LoginControllor {

    @Autowired
    UserService userService;
    //登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public List<Message> Login(@RequestBody Map map){

        String username= (String) map.get("username");
        String password= (String) map.get("password");

        User user=userService.getPasswordByUser(username);
        List<Message> list=new ArrayList<>();
        Message message=new Message();

        if(username.equals(user.getUsername())&&password.equals(user.getPassword())){
            //生成一个token
            String token= JwtUtil.createToken(user);
            System.out.println(token);
            message.setToken(token);
            message.setUser(user);
            message.setMsg("登陆成功");
            message.setCode(200);
            list.add(message);
        }
        else {
            message.setMsg("用户密码错误");
            message.setCode(400);
            list.add(message);
        }
       return list;
    }
    //注册
    @RequestMapping(value = "/Register",method = RequestMethod.POST)
    public List<Message> UserRegister(@RequestBody Map map){
        String username= (String) map.get("username");
        String password= (String) map.get("password");
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        userService.UserRegister(user);
        List<Message> list=new ArrayList<>();
        Message message=new Message();
        message.setCode(200);
        message.setMsg("注册成功");
        list.add(message);
        return list;
    }


    @GetMapping("/checkToken")
    public Boolean checkToken(HttpServletRequest request){

        String token=request.getHeader("Authorization");
        System.out.println("==========================================");
        System.out.println("检查toke......");
        if(JwtUtil.checkToken(token)){
            System.out.println("检查完毕!");
        }

        return JwtUtil.checkToken(token);
    }
    //用户信息
    @RequestMapping("/getUser")
    public List<User> getUser(){
        return userService.getUser();
    }
}
